package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.article.pojo.ApAuthor;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.article.feign.ApAuthorFeign;
import com.itheima.wemedia.feign.WmUserFeign;
import com.itheima.user.dto.ApUserRealnamePageRequestDto;
import com.itheima.user.mapper.ApUserMapper;
import com.itheima.user.pojo.ApUser;
import com.itheima.user.pojo.ApUserRealname;
import com.itheima.user.mapper.ApUserRealnameMapper;
import com.itheima.user.service.ApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.wemedia.pojo.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @version 1.0
 * @description <p>APP实名认证信息 业务实现</p>
 * @package com.itheima.user.service.impl
 */
@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private WmUserFeign wmUserFeign;

    @Autowired
    private ApAuthorFeign apAuthorFeign;

    /**
     * 分页查询
     * @param dto
     * @return
     */
    public PageResultVo<ApUserRealname> findPage(ApUserRealnamePageRequestDto dto){
        //分页参数
        Page<ApUserRealname> pageInfo = new Page<>(dto.getPage(), dto.getSize());
        //条件状态判断
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery().eq(null != dto.getStatus(), ApUserRealname::getStatus, dto.getStatus());
        //分页查询
        page(pageInfo,queryWrapper);
        //返回结果
        return PageResultVo.pageResult(dto.getPage(), dto.getSize(), pageInfo.getTotal(), pageInfo.getRecords());

    }

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    /*   @Override
    public PageResultVo<ApUserRealname> findPage(ApUserRealnamePageRequestDto dto) {
        //1. 分页参数设置
        IPage<ApUserRealname> pageInfo = new Page<ApUserRealname>(dto.getPage(), dto.getSize());
        //2. 条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery()
                .eq(null != dto.getStatus(), ApUserRealname::getStatus, dto.getStatus());
        //3. 查询
        page(pageInfo, queryWrapper);
        //4. 构造返回
        return PageResultVo.pageResult(dto.getPage(), dto.getSize(), pageInfo.getTotal(), pageInfo.getRecords());
    }*/


    /**
     * 实名审核通过
     *
     * @param
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void authPass(Map<String, Object> paramMap) {
        //1. 参数校验
        Integer id = (Integer) paramMap.get("id");
        //非空判断，错误抛出500
        if (null == id) {
            throw new LeadNewsException(HttpCodeEnum.PARAM_REQUIRE);
        }
        //2. 更新实名认证的状态 update table set .... where id=-100; 0
        ApUserRealname pojo = new ApUserRealname();

        pojo.setId(Math.toIntExact(id.longValue()));
        //填充修改时间
        pojo.setUpdatedTime(LocalDateTime.now());
        //设置状态=9审核通过
        pojo.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_PASS);
        //-----更新信息
        updateById(pojo);
        //3. 更新用户信息，认证通过、flag为自媒体人
        //-----通过id查询到用户信息
        ApUserRealname userRealname = getById(id); // -100
        if (null == userRealname) {
            //错误抛出异常：数据不存在
            throw new LeadNewsException(HttpCodeEnum.DATA_NOT_EXIST);
        }

        Integer appUserId = userRealname.getUserId();
        // 更新用户信息
        ApUser apUser = new ApUser();
        apUser.setId(appUserId);
        // 设置为已认证=1
        apUser.setIsIdentityAuthentication(BusinessConstants.ApUserConstants.AUTHENTICATED);
        // 设置为自媒体人=1
        apUser.setFlag(BusinessConstants.ApUserConstants.FLAG_WEMEDIA);
        //------更新信息
        apUserMapper.updateById(apUser);


        //TODO 4. 远程调用(自媒体微服务)创建自媒体账号
        ApUser appUserInfo = apUserMapper.selectById(appUserId);
        Integer wmUserId = addWmuser(appUserId, appUserInfo);
        log.debug("实名认证 添加自媒体账号成功：id={}, appUserId={},wmUserId={}", id, appUserId, wmUserId);
        //TODO 5. 远程调用创建(文章微服务)作者账号--
        addApAuthor(wmUserId,appUserInfo);
        log.debug("实名认证 添加作者账号成功：id={}, appUserId={},wmUserId={}", id, appUserId, wmUserId);

    }


    /**
     * 添加自媒体账号
     *
     * @param appUserId
     * @param apUserInfo
     * @return
     */
    private Integer addWmuser(Integer appUserId, ApUser apUserInfo) {
        //远程调用通过appUserId查询自媒体账号信息
        ResultVo<WmUser> wmUserResult = wmUserFeign.getByAppUserId(appUserId);
        if (!wmUserResult.isSuccess()) {
            throw new LeadNewsException("调用自媒体微服务失败。");
        }
        //填充信息
        WmUser wmUser = wmUserResult.getData();
        if (wmUser == null) {
            wmUser = new WmUser();
            BeanUtils.copyProperties(apUserInfo, wmUser);
            wmUser.setId(null);
            wmUser.setApUserId(appUserId);
            wmUser.setNickname(apUserInfo.getName());
            wmUser.setType(BusinessConstants.WmUserConstants.TYPE_PERSONAL);
            wmUser.setStatus(BusinessConstants.WmUserConstants.STATUS_OK);
            wmUser.setCreatedTime(LocalDateTime.now());
            //远程调用，添加自媒体账号
            ResultVo<WmUser> inserResult = wmUserFeign.save(wmUser);
            if (!inserResult.isSuccess()) {
                throw new LeadNewsException("调用自媒体微服务失败。");
            }
            //获取响应数据
            wmUser = inserResult.getData();
        }
        return Math.toIntExact(wmUser.getId());
    }

    /**
     * 添加作者信息
     *
     * @param wmUserId
     * @param apUserInfo
     */
    private void addApAuthor(Integer wmUserId, ApUser apUserInfo) {
        //远程调用，通过用户id与自媒体账号id获取作者信息
        ResultVo<ApAuthor> getResult = apAuthorFeign.getByApUserIdWmUser(apUserInfo.getId(), wmUserId);
        if (!getResult.isSuccess()) {
            throw new LeadNewsException("调用文章微服务失败，查询作者信息失败。");
        }

        ApAuthor author = getResult.getData();
        //填充信息
        if (author == null) {
            author = new ApAuthor();
            author.setName(apUserInfo.getName());
            author.setType(BusinessConstants.ApAuthorConstants.A_MEDIA_USER);
            author.setUserId(Long.valueOf(apUserInfo.getId()));
            author.setWmUserId(wmUserId);
            author.setCreatedTime(LocalDateTime.now());
            //远程调用，创建作者账号
            ResultVo addResult = apAuthorFeign.add(author);
            if (!addResult.isSuccess()) {
                throw new LeadNewsException("调用文章微服务失败，查询作者信息失败。");
            }
        }
    }



    /**
     * 实名审核驳回
     *
     * @param paramMap
     */
    @Override
    public void authFail(Map<String, Object> paramMap) {
        // 获取参数
        Integer keyId = (Integer) paramMap.get("id");
        String reason = (String) paramMap.get("msg");
        // 构建更新的对象
        ApUserRealname pojo = new ApUserRealname();
        // 设置修改信息
        pojo.setReason(reason);
        pojo.setId(Math.toIntExact(Long.valueOf(keyId)));
        //设置状态为2=已驳回
        pojo.setStatus(BusinessConstants.ApUserRealnameConstants.AUTH_REJECT);
        //填充更新时间为当前时间
        pojo.setUpdatedTime(LocalDateTime.now());
        // 更新
        updateById(pojo);
    }


}
